<template>
  <div>
    <div class="btn" @click="showPop">选择</div>
    <van-popup v-model:show="showPicker" round position="bottom">
      <van-picker
        :key="keyValue"
        :default-index="selectIndex"
        ref="picker"
        swipe-duration="2000"
        show-toolbar
        value-key="name"
        :columns="state.pickerOptions"
        :columns-field-names="{ text: 'name', value: 'code' }"
        @cancel="showPicker = false"
        @confirm="confirm"
      ></van-picker>
    </van-popup>
  </div>
</template>

<script setup>
import { onBeforeMount, watch, ref, reactive } from 'vue'
import { dictStore } from '@/pinia/modules/dict.js'

const props = defineProps({
  // 字典code
  code: {
    require: true,
    default: 'JGLX'
  },
  // 回显值
  modelValue: {
    require: false,
    default: ''
  }
})
const emit = defineEmits(['update:value', 'change'])

const comValue = ref('')
const selectIndex = ref(0)
const showPicker = ref(false)
const keyValue = ref('')
const state = reactive({
  pickerOptions: []
})

watch(
  () => props.modelValue,
  val => {
    if (val || val === 0 || val === '0') {
      let index = state.pickerOptions.findIndex(item => item.code == val)
      comValue.value = state.pickerOptions[index].name
      selectIndex.value = index
    } else {
      comValue.value = ''
      selectIndex.value = 0
    }
  },
  { deep: true }
)

const showPop = () => {
  if (props.disabled) {
    return
  }
  showPicker.value = true
}

const confirm = val => {
  comValue.value = val.selectedOptions[0].name
  emit('update:value', val.selectedOptions[0].code)
  emit('change', val.selectedOptions[0])
  showPicker.value = false
}

const initCode = () => {
  let target = dictStore().dict.find(item => item.code == props.code)
  let arr = []
  if (target && target.children.length > 0) {
    target.children.forEach(item => {
      arr.push({ code: item.code, name: item.name })
    })
  }
  state.pickerOptions = arr
  keyValue.value = new Date().getTime()
  console.log(arr)
}

onBeforeMount(() => {
  initCode()
  console.log(dictStore().dict)
})
</script>
<style lang="less" scoped>
:deep(.van-field__control::-webkit-input-placeholder) {
  color: #000;
}
:deep(.van-cell) {
  background-color: #ffffff00;
}

.btn {
  font-size: 36px;
  color: #4293f4;
}
</style>
